package main

import (
    "bufio"
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
)

const (
    baseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
    model   = "qwen-plus"
    apiKey  = "sk-28e5a3bbcfe044d1a799b9571fe35b13"
)

type Message struct {
    Role    string `json:"role"`
    Content string `json:"content"`
}

type Request struct {
    Model    string    `json:"model"`
    Messages []Message `json:"messages"`
}

type Response struct {
    Choices []struct {
        Message struct {
            Content string `json:"content"`
        } `json:"message"`
    } `json:"choices"`
}

func main() {
    fmt.Println("欢迎使用 AI 聊天程序！输入 'quit' 退出。")
    scanner := bufio.NewScanner(os.Stdin)
    
    for {
        fmt.Print("\n请输入您的问题: ")
        if !scanner.Scan() {
            break
        }
        
        userInput := scanner.Text()
        if userInput == "quit" {
            break
        }

        response, err := chatWithAI(userInput)
        if err != nil {
            fmt.Printf("错误: %v\n", err)
            continue
        }

        fmt.Printf("\nAI 回答: %s\n", response)
    }
}

func chatWithAI(userInput string) (string, error) {
    messages := []Message{
        {Role: "user", Content: userInput},
    }

    requestBody := Request{
        Model:    model,
        Messages: messages,
    }

    jsonData, err := json.Marshal(requestBody)
    if err != nil {
        return "", fmt.Errorf("JSON编码错误: %v", err)
    }

    req, err := http.NewRequest("POST", baseURL+"/chat/completions", bytes.NewBuffer(jsonData))
    if err != nil {
        return "", fmt.Errorf("创建请求失败: %v", err)
    }

    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", "Bearer "+apiKey)

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return "", fmt.Errorf("发送请求失败: %v", err)
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return "", fmt.Errorf("读取响应失败: %v", err)
    }

    if resp.StatusCode != http.StatusOK {
        return "", fmt.Errorf("API请求失败，状态码: %d，响应: %s", resp.StatusCode, string(body))
    }

    var response Response
    if err := json.Unmarshal(body, &response); err != nil {
        return "", fmt.Errorf("解析响应失败: %v", err)
    }

    if len(response.Choices) == 0 {
        return "", fmt.Errorf("AI没有返回答案")
    }

    return response.Choices[0].Message.Content, nil
} 